package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.admin.feign.ArticleFeign;
import com.heima.admin.feign.WemediaFeign;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.fastdfs.util.FastDFSClientUtil;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    /**
     * 自媒体文章审核
     *
     * @param id
     */
    @Override
    public void autoScanByMediaNewsId(Integer id) {
        if (id == null) {
            log.error("当前的审核ID为Null");
            return;
        }
        //1.根据id查询自媒体文章信息
        ResponseResult<WmNews> result = wemediaFeign.findById(id);
        if (result.getCode() != AppHttpCodeEnum.SUCCESS.getCode() || result.getData() == null) {
            throw new RuntimeException("根据id查询自媒体文章信息出错"+result.getCode()+" "+ result.getData());
        }
        WmNews wmNews = result.getData();
        //2.文章状态为4（人工审核通过）直接保存数据和创建索引
        if (wmNews.getStatus() == 4) {
            saveAppArticle(wmNews);
            return;
        }
        //3.文章状态为8  发布时间小于等于当前时间 直接保存数据
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= new Date().getTime()) {
            saveAppArticle(wmNews);
            return;
        }
        //4.文章状态为1，待审核
        if (wmNews.getStatus() == 1) {
            //抽取文章的文本和图片
            Map<String, Object> map = handleTextAndImages(wmNews);
            //4.1 文本审核
            boolean content = handleTextScan((String) map.get("content"), wmNews);
            if (!content) return;
            //4.2 图片审核
            content = handleImagesScan((List<String>) map.get("images"), wmNews);
            if (!content) return;
            //4.3 自管理敏感词审核
            content = handleSensitive((String) map.get("content"), wmNews);
            if (!content) return;
            //4.4 发布时间大于当前时间，
            if (wmNews.getPublishTime().getTime() > new Date().getTime()) {
                //修改文章状态为8
                wmNews.setStatus((short) 8);
                wmNews.setReason( "审核通过，待发布");
                updateWmNews(wmNews);
                return;
            }
            //5.审核通过，修改自媒体文章状态为9  保存app端相关文章信息
            saveAppArticle(wmNews);
        }


    }



    @Autowired
    private AdSensitiveMapper adSensitiveMapper;
    /**
     * 自管理铭感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        List<String> allSensitive = adSensitiveMapper.findAllSensitive();
        //初始化敏感词
        SensitiveWordUtil.initMap(allSensitive);
        //文章内容自管理敏感词过滤
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if (resultMap.size() > 0) {
            log.error("敏感词过滤没有通过，包含了敏感词:{}", resultMap);
            //找到了敏感词，审核不通过
            wmNews.setStatus((short) 2);
            wmNews.setReason("文章中包含了敏感词");
            updateWmNews(wmNews);
            flag = false;
        }

        return flag;
    }

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Value("${fdfs.url}")
    private String fileServerUrl;


    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        if (images == null) {
            return true;
        }
        boolean flag = true;
        List<byte[]> imageList = new ArrayList<>();
        try {
            for (String image : images) {
                String imageName = image.replace(fileServerUrl, "");
                int index = imageName.indexOf("/");
                String groupName = imageName.substring(0, index);
                String imagePath = imageName.substring(index + 1);
                byte[] imageByte = fastDFSClientUtil.download(groupName, imagePath);
                imageList.add(imageByte);
            }
            Map<String, String> map = greenImageScan.imageScan(imageList);
            if (!map.get("suggestion").equals("pass")){
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    //修改文章状态，并告知审核失败原因
                    wmNews.setStatus((short) 2);
                    wmNews.setReason("文章图片有违规");
                    updateWmNews(wmNews);
                    flag = false;

                }
                //需要仍审核
                if (map.get("suggestion").equals("review")) {
                    //修改文章状态，并告知审核失败原因wmNews
                    wmNews.setStatus((short) 3);
                    wmNews.setReason("文章图片中有不确定因素，人工审核中...");
                    updateWmNews(wmNews);
                    flag = false;
                }
            }
            return flag;
        } catch (Exception e) {
            log.error("自动审核图片失败！",e);
            return false;
        }
    }

    @Autowired
    private GreeTextScan greeTextScan;

    /**
     * 文本审核
     *
     * @param content
     * @param wmNews
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        Map<String, String> map = null;
        boolean flag = true;
        try {
            map = greeTextScan.greeTextScan(content);
        } catch (Exception e) {
            log.error("文本自动审核出错", e);
            return false;
        }
        //自动审核不通过
        if (!map.get("suggestion").equals("pass")) {
            //审核失败
            if (map.get("suggestion").equals("block")) {
                //修改文章状态，并告知审核失败原因
                wmNews.setStatus((short) 2);
                wmNews.setReason("文章内容中有敏感词汇(自动审核)");
                updateWmNews(wmNews);
                flag = false;

            }
            //需要仍审核
            if (map.get("suggestion").equals("review")) {
                //修改文章状态，并告知审核失败原因wmNews
                wmNews.setStatus((short) 3);
                wmNews.setReason("文章中有不确定词汇，人工审核中...");
                updateWmNews(wmNews);
                flag = false;
            }
        }
        return flag;
    }

    void updateWmNews(WmNews wmNews) {
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (result.getCode() != AppHttpCodeEnum.SUCCESS.getCode()) {
            throw new RuntimeException("更新文章状态失败！");
        }
    }

    /**
     * 获取文本内容和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //文章的内容
        String content = wmNews.getContent();

        //存储纯文本内容
        StringBuilder sb = new StringBuilder();
        //存储图片
        List<String> images = new ArrayList<>();

        //获取标题文本
        sb.append(wmNews.getTitle()).append("\n");

        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for (Map map : contentList) {
            if (map.get("type").equals("text")) {
                sb.append(map.get("value"));
            }

            if (map.get("type").equals("image")) {
                images.add((String) map.get("value"));
            }
        }

        if (wmNews.getImages() != null && wmNews.getType() != 0) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", sb.toString());
        resultMap.put("images", images);
        return resultMap;
    }

    @Autowired
    AdChannelMapper adChannelMapper;

    /**
     * 保存app文章相关的数据
     *
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews) {
        //保存app文章
        ApArticle apArticle = saveArticle(wmNews);
        //保存app文章配置
        saveArticleConfig(apArticle);
        //保存app文章内容
        saveArticleContent(apArticle,wmNews);
        //修改自媒体文章的状态为9
        wmNews.setArticleId(apArticle.getId());
        wmNews.setStatus((short) 9);
        wmNews.setReason("审核通过");
        updateWmNews(wmNews);
        //TODO es索引创建

    }

    /**
     * 创建app端文章内容信息
     * @param apArticle
     * @param wmNews
     */
    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        ResponseResult result = articleFeign.saveArticleContent(apArticleContent);
        if (result.getCode() != AppHttpCodeEnum.SUCCESS.getCode()) {
            throw new RuntimeException("创建app端文章内容信息数据出错！");
        }
    }

    /**
     * 创建app端文章配置信息
     * @param apArticle
     */
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        ResponseResult result = articleFeign.saveArticleConfig(apArticleConfig);
        if (result.getCode() != AppHttpCodeEnum.SUCCESS.getCode()) {
            throw new RuntimeException("创建app端文章内容信息数据出错！");
        }
    }


    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());
        //获取作者相关信息
        Integer wmUserId = wmNews.getUserId();
        ResponseResult<WmUser> result = wemediaFeign.findWmUserById(wmUserId);
        if (result.getCode() != AppHttpCodeEnum.SUCCESS.getCode()||result.getData()==null) {
            throw new RuntimeException("查询作者相关信息失败！"+result.getCode()+" "+ result.getData());
        }
        WmUser wmUser = result.getData();
        String wmUserName = wmUser.getName();
        ResponseResult<ApAuthor> apAuthorResponseResult = articleFeign.selectAuthorByName(wmUserName);
        if (apAuthorResponseResult.getCode() != AppHttpCodeEnum.SUCCESS.getCode()||apAuthorResponseResult.getData()==null) {
            throw new RuntimeException("查询作者相关信息失败！");
        }
        ApAuthor apAuthor = apAuthorResponseResult.getData();
        apArticle.setAuthorId(apAuthor.getId().longValue());
        apArticle.setAuthorName(apAuthor.getName());
        //获取频道相关信息
        Integer channelId = wmNews.getChannelId();
        AdChannel channel = adChannelMapper.selectById(channelId);
        if(channel != null){
            apArticle.setChannelId(channel.getId());
            apArticle.setChannelName(channel.getName());
        }

        ResponseResult result1 = articleFeign.saveArticle(apArticle);
        if (result1.getCode() != AppHttpCodeEnum.SUCCESS.getCode()) {
            throw new RuntimeException("保存App端文章数据出错！");
        }
        return apArticle;
    }

}